package com.cyj.qqclient.service;

import com.cyj.qqcommon.Message;
import com.cyj.qqcommon.MessageType;

import java.io.*;
import java.util.Date;

/**
 * 文件传输服务
 *
 */
public class FileClientService {
    public static void sendFile(String src,String dest,String senderId,String getterID) {
        Message message=new Message();
        message.setMessageType(MessageType.MESSAGE_FILE_MES);
        message.setSender(senderId);
        message.setGetter(getterID);
        message.setSrc(src);
        message.setDest(dest);

        FileInputStream fis=null;
        byte[] fileBytes=new byte[(int)new File(src).length()];

        try {
            fis =new FileInputStream(src);
            fis.read(fileBytes);//把src文件读入程序的字节数组

            message.setFileBytes(fileBytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        System.out.println("\n"+senderId+"给"+getterID+"发送文件："+src+
                "到对方电脑目录 "+dest+ new Date().toString());

        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(ManageClientConnectSeverThread.getClientConnectServerThread(senderId).getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
